<template>
  <div class="nav-list-container">
    <van-list
      v-model:loading="listIsLoading"
      :finished="finished"
      finished-text="没吃的了"
      error-text="没吃的了"
      :error="error"
      @load="onLoad"
    >
      <NavListItem v-for="item in originData" :key="item.id" :data="item" />
    </van-list>
  </div>
  </template>
  
  <script setup>
  import { ref, watch } from 'vue'
  import NavListItem from './NavListItem.vue'
  
  const props = defineProps({
    data: {
      type: Array,
      default: () => []
    }
  })
  
  const emit = defineEmits(['update:listIsLoading', 'load-more'])
  
  const originData = ref([])
  const listIsLoading = ref(false)
  const finished = ref(false)
  const error = ref(false)
  
  watch(() => props.data, (newData) => {
    if (newData && newData.length > 0) {
      originData.value = [...newData]
      finished.value = false
      error.value = false
    } else if (newData && newData.length === 0) {
      // 如果传入空数组，重置状态
      originData.value = []
      finished.value = false
      error.value = false
    }
  }, { immediate: true })
  
  const onLoad = () => { 
    listIsLoading.value = true
    emit('update:listIsLoading', true)
    emit('load-more')
  }
  
  const addData = (newData) => {
    if (newData && newData.length > 0) {
      originData.value.push(...newData)
      listIsLoading.value = false
      error.value = false
      
      if (newData.length < 3) {
        finished.value = true
      }
    } else {
      finished.value = true
      listIsLoading.value = false
    }
    emit('update:listIsLoading', false)
  }
  
  const setError = () => {
    error.value = true
    listIsLoading.value = false
    emit('update:listIsLoading', false)
  }
  
  defineExpose({
    addData,
    setError
  })
  </script>
  
  <style scoped lang="scss">
  .nav-list-container {
    min-height: 200px;
    background-color: #fff;
    
    :deep(.van-list__finished-text) {
      color: #999;
      font-size: 14px;
      padding: 20px 0;
      text-align: center;
    }
    
    :deep(.van-list__error-text) {
      color: #ff6b6b;
      font-size: 14px;
      padding: 20px 0;
      text-align: center;
    }
    
    :deep(.van-loading) {
      padding: 20px 0;
    }
  }
  </style>